const { DailySentence, DailyRecord, User } = require('./model');
const { Op } = require('sequelize');

class DailyDao {
  // 每日一句相关操作
  
  // 创建每日一句
  async createDailySentence(sentenceData) {
    try {
      return await DailySentence.create(sentenceData);
    } catch (error) {
      throw new Error(`创建每日一句失败: ${error.message}`);
    }
  }

  // 获取每日一句列表
  async getDailySentences(options = {}) {
    try {
      const { page = 1, limit = 10, difficulty, keyword, startDate, endDate } = options;
      const offset = (page - 1) * limit;
      
      const whereClause = {};
      if (difficulty) whereClause.difficulty = difficulty;
      if (keyword) {
        whereClause[Op.or] = [
          { chinese: { [Op.like]: `%${keyword}%` } },
          { pinyin: { [Op.like]: `%${keyword}%` } },
          { english: { [Op.like]: `%${keyword}%` } }
        ];
      }
      if (startDate && endDate) {
        whereClause.date = {
          [Op.between]: [startDate, endDate]
        };
      }

      const { count, rows } = await DailySentence.findAndCountAll({
        where: whereClause,
        order: [['date', 'DESC']],
        limit: parseInt(limit),
        offset: parseInt(offset)
      });

      return {
        sentences: rows,
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(count / limit)
      };
    } catch (error) {
      throw new Error(`获取每日一句列表失败: ${error.message}`);
    }
  }

  // 根据日期获取每日一句
  async getDailySentenceByDate(date) {
    try {
      return await DailySentence.findOne({
        where: { date }
      });
    } catch (error) {
      throw new Error(`获取每日一句失败: ${error.message}`);
    }
  }

  // 获取今日一句
  async getTodaySentence() {
    try {
      const today = new Date().toISOString().split('T')[0];
      return await this.getDailySentenceByDate(today);
    } catch (error) {
      throw new Error(`获取今日一句失败: ${error.message}`);
    }
  }

  // 根据ID获取每日一句
  async getDailySentenceById(id) {
    try {
      return await DailySentence.findByPk(id);
    } catch (error) {
      throw new Error(`获取每日一句失败: ${error.message}`);
    }
  }

  // 更新每日一句
  async updateDailySentence(id, updateData) {
    try {
      const [updatedRowsCount] = await DailySentence.update(updateData, {
        where: { id }
      });
      
      if (updatedRowsCount === 0) {
        throw new Error('每日一句不存在');
      }
      
      return await this.getDailySentenceById(id);
    } catch (error) {
      throw new Error(`更新每日一句失败: ${error.message}`);
    }
  }

  // 增加查看次数
  async incrementViewCount(id) {
    try {
      const sentence = await this.getDailySentenceById(id);
      if (!sentence) {
        throw new Error('每日一句不存在');
      }

      return await this.updateDailySentence(id, {
        view_count: sentence.view_count + 1
      });
    } catch (error) {
      throw new Error(`增加查看次数失败: ${error.message}`);
    }
  }

  // 增加练习次数
  async incrementPracticeCount(id) {
    try {
      const sentence = await this.getDailySentenceById(id);
      if (!sentence) {
        throw new Error('每日一句不存在');
      }

      return await this.updateDailySentence(id, {
        practice_count: sentence.practice_count + 1
      });
    } catch (error) {
      throw new Error(`增加练习次数失败: ${error.message}`);
    }
  }

  // 删除每日一句
  async deleteDailySentence(id) {
    try {
      const deletedRowsCount = await DailySentence.destroy({
        where: { id }
      });
      
      if (deletedRowsCount === 0) {
        throw new Error('每日一句不存在');
      }
      
      return true;
    } catch (error) {
      throw new Error(`删除每日一句失败: ${error.message}`);
    }
  }

  // 每日朗读记录相关操作

  // 创建每日朗读记录
  async createDailyRecord(recordData) {
    try {
      return await DailyRecord.create(recordData);
    } catch (error) {
      throw new Error(`创建每日朗读记录失败: ${error.message}`);
    }
  }

  // 获取用户每日朗读记录
  async getUserDailyRecords(userId, options = {}) {
    try {
      const { page = 1, limit = 10, startDate, endDate } = options;
      const offset = (page - 1) * limit;
      
      const whereClause = { user_id: userId };
      if (startDate && endDate) {
        whereClause.created_at = {
          [Op.between]: [startDate, endDate]
        };
      }

      const { count, rows } = await DailyRecord.findAndCountAll({
        where: whereClause,
        include: [{
          model: DailySentence,
          as: 'dailySentence'
        }],
        order: [['created_at', 'DESC']],
        limit: parseInt(limit),
        offset: parseInt(offset)
      });

      return {
        records: rows,
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(count / limit)
      };
    } catch (error) {
      throw new Error(`获取用户每日朗读记录失败: ${error.message}`);
    }
  }

  // 根据ID获取每日朗读记录
  async getDailyRecordById(id) {
    try {
      return await DailyRecord.findByPk(id, {
        include: [{
          model: DailySentence,
          as: 'dailySentence'
        }, {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'nickname', 'avatar']
        }]
      });
    } catch (error) {
      throw new Error(`获取每日朗读记录失败: ${error.message}`);
    }
  }

  // 获取用户今日朗读记录
  async getUserTodayRecord(userId) {
    try {
      const today = new Date();
      const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate());
      const endOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);

      return await DailyRecord.findOne({
        where: {
          user_id: userId,
          created_at: {
            [Op.between]: [startOfDay, endOfDay]
          }
        },
        include: [{
          model: DailySentence,
          as: 'dailySentence'
        }],
        order: [['created_at', 'DESC']]
      });
    } catch (error) {
      throw new Error(`获取用户今日朗读记录失败: ${error.message}`);
    }
  }

  // 更新每日朗读记录
  async updateDailyRecord(id, updateData) {
    try {
      const [updatedRowsCount] = await DailyRecord.update(updateData, {
        where: { id }
      });
      
      if (updatedRowsCount === 0) {
        throw new Error('每日朗读记录不存在');
      }
      
      return await this.getDailyRecordById(id);
    } catch (error) {
      throw new Error(`更新每日朗读记录失败: ${error.message}`);
    }
  }

  // 删除每日朗读记录
  async deleteDailyRecord(id) {
    try {
      const deletedRowsCount = await DailyRecord.destroy({
        where: { id }
      });
      
      if (deletedRowsCount === 0) {
        throw new Error('每日朗读记录不存在');
      }
      
      return true;
    } catch (error) {
      throw new Error(`删除每日朗读记录失败: ${error.message}`);
    }
  }

  // 获取用户每日朗读统计
  async getUserDailyStats(userId) {
    try {
      const totalRecords = await DailyRecord.count({
        where: { user_id: userId }
      });

      const avgScore = await DailyRecord.findOne({
        where: { user_id: userId },
        attributes: [
          [DailyRecord.sequelize.fn('AVG', DailyRecord.sequelize.col('score')), 'avgScore'],
          [DailyRecord.sequelize.fn('MAX', DailyRecord.sequelize.col('score')), 'maxScore']
        ],
        raw: true
      });

      return {
        totalRecords,
        averageScore: parseFloat(avgScore?.avgScore || 0).toFixed(2),
        bestScore: parseFloat(avgScore?.maxScore || 0).toFixed(2)
      };
    } catch (error) {
      throw new Error(`获取用户每日朗读统计失败: ${error.message}`);
    }
  }
}

module.exports = new DailyDao();
